#include "./include/2440addr.h"
#include "./include/sys_dbg.h"
#include "./include/led.h"

//LED硬件数量
#define LED_HW_COUNT (4)
#define LED_DISP_NUM_MASK (_BIT(LED_HW_COUNT)-1)
#define LED_GPBDATA_START_BIT (5)
#define CONVERT_INDEX_TO_REGBIT(i) (LED_GPBDATA_START_BIT+LED_HW_COUNT-i-1)
//开发板从左至右，一次为led0~led3

void led_init(void){
    //初始状态为全灭
    INT32 val=0;
    for(INT32 i=0;i<LED_HW_COUNT;i++){
        val = 3<<(2*(LED_GPBDATA_START_BIT+i));
        rGPBCON &= ~val;
        rGPBCON |= _BIT(2*(LED_GPBDATA_START_BIT+i));
    }

	rGPBUP |= (LED_DISP_NUM_MASK<<LED_GPBDATA_START_BIT);
	led_turnOffAll();
}

INT32 led_getCount(void){
    return LED_HW_COUNT;
}

void led_turnOn(INT32 ledIdx){
    SYS_ASSERT(ledIdx>=0&&ledIdx<LED_HW_COUNT);
    rGPBDAT &= ~(1<<(CONVERT_INDEX_TO_REGBIT(ledIdx)));
}

void led_turnOff(INT32 ledIdx){
    SYS_ASSERT(ledIdx>=0&&ledIdx<LED_HW_COUNT);
    rGPBDAT |= (1<<(CONVERT_INDEX_TO_REGBIT(ledIdx)));
}
void led_turnOnAll(void){
    INT32 val = ~(LED_DISP_NUM_MASK<<LED_GPBDATA_START_BIT);
    rGPBDAT &= val;
}
void led_turnOffAll(void){
    INT32 val = LED_DISP_NUM_MASK<<LED_GPBDATA_START_BIT;
    rGPBDAT|=val;
}
//每调用一次该函数，灯的状态
void led_toggle(INT32 ledIdx){
    SYS_ASSERT(ledIdx>=0 && ledIdx<LED_HW_COUNT);
    INT32 val = rGPBDAT & _BIT(CONVERT_INDEX_TO_REGBIT(ledIdx));
    if(val)
        led_turnOn(ledIdx);
    else
        led_turnOff(ledIdx);
}

void led_multiToggle(INT32 mask){
    mask &= LED_DISP_NUM_MASK;
    for(INT32 i=0;i<LED_HW_COUNT;i++){
        if(mask & _BIT(i))
            led_toggle(i);
    }
}
void led_dispnum(INT32 num){
    num &= LED_DISP_NUM_MASK;
    for(INT32 i=0;i<LED_HW_COUNT;i++){
        if(num & _BIT(i))
            led_turnOn(i);
        else
            led_turnOff(i);
    }
}


// void led_disp_data32(unsigned int num)
// {
// 	int flagBit=1<<3;
// 	unsigned int dispData=0;
// 	int startIndex=0;
// 	int endIndex;
// 	int j;
// 	do{
// 		dispData=0;
// 		led_disp_num(dispData);
// 		delay(100);
// 		dispData=flagBit;
// 		endIndex=startIndex+2;
// 		if(endIndex>=31)
// 			endIndex=31;
// 		for(j=startIndex;j<=endIndex;j++){
// 			if(num &(1<<j))
// 				dispData |= 1<<(j-startIndex);
// 			else
// 				dispData &= ~(1<<(j-startIndex));
// 		}
// 		led_disp_num(dispData);
// 		delay(100);
// 		startIndex=endIndex+1;
// 	}while(endIndex<31);
// 	delay(300);
// }
